package com.cn.easy.export.util

import com.cn.easy.export.model.enumerate.ExcelImageType
import com.cn.easy.export.model.excel.ExcelCoordinateValue
import com.cn.easy.export.model.excel.ExcelImage
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.RichTextString
import org.apache.poi.ss.usermodel.Sheet
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*

/**
 * 向单元格中写入数据
 */
fun <T> setCellValue(cell: Cell, value: T?) {
    when (value) {
        is String -> cell.setCellValue(value)
        is Date -> cell.setCellValue(value)
        is Double -> cell.setCellValue(value)
        is LocalDate -> cell.setCellValue(value)
        is LocalDateTime -> cell.setCellValue(value)
        is Calendar -> cell.setCellValue(value)
        is RichTextString -> cell.setCellValue(value)
        is ExcelImage -> writeImage(cell, value)
        else -> {
            if (value != null) {
                cell.setCellValue(value.toString())
            } else {
                cell.setBlank()
            }
        }
    }
}

fun writeImage(cell: Cell, value: ExcelImage) {
    val row = cell.row
    val sheet = cell.sheet

    val workbook = sheet.workbook
    val pictureIdx = workbook.addPicture(value.bytes, value.type.value);

    val drawing = sheet.createDrawingPatriarch();
    // 创建一个锚点对象
    val anchor = drawing.createAnchor(0, 0, 0, 0, cell.columnIndex, row.rowNum, cell.columnIndex + 1, row.rowNum + 1);

    // 插入图片
    drawing.createPicture(anchor, pictureIdx);

}

fun autoWidthAndHeight(data: List<ExcelCoordinateValue<*>>, sheet: Sheet, dataStartRowIndex: Int) {
    val isExcelImage = { value: ExcelCoordinateValue<*> -> value.value != null && value.value is ExcelImage }
    if (data.any { isExcelImage(it) }) {
        data.filter { isExcelImage(it) }
            .groupBy { it.coordinate1.col }
            .forEach { (col, values) ->
                val maxWidth = values.map { it.value as ExcelImage }.maxOf { it.width }
                sheet.setColumnWidth(col, maxWidth)
            }

        // 根据图片设置行高
        val maxHeight = data.filter { isExcelImage(it) }.map { it.value as ExcelImage }.maxOf { it.height }
        for (rowIndex in dataStartRowIndex until sheet.lastRowNum) {
            sheet.getRow(rowIndex)?.let { row ->
                row.height = maxHeight.toShort()
            }
        }
    }


}

fun parseImageTypeByFilename(filename: String): ExcelImageType {
    return when (filename.substringAfterLast(".").lowercase()) {
        "png" -> ExcelImageType.PNG
        "jpg", "jpeg" -> ExcelImageType.JPEG
        "emf" -> ExcelImageType.EMF
        "wmf" -> ExcelImageType.WMF
        "pict" -> ExcelImageType.PICT
        "dib" -> ExcelImageType.DIB
        else -> ExcelImageType.PNG
    }
}